﻿param($DllSourceDir,$ReleaseTargetDir,$ServiceName,$ProcessName)
Write-Host $DllSourceDir
if ([string]::IsNullOrEmpty($DllSourceDir))
{
    Write-Error "请传递DLL源文件地址"
}
if ([string]::IsNullOrEmpty($ReleaseTargetDir))
{
    Write-Error "请传递发布部署目标地址"
}
if ([string]::IsNullOrEmpty($ServiceName))
{
    Write-Error "请传递部署服务名称"
}
if ([string]::IsNullOrEmpty($ProcessName))
{
    Write-Error "请传递部署服务的进程名称"
}

#先判断编译DLL的文件夹是否存在
[bool]$exitDir = Test-Path $DllSourceDir
if (!$exitDir)
{
    Write-Error "文件夹：$DllSourceDir 不存在"
    exit
}
[bool]$exitDll = Test-Path $DllSourceDir\*.*
if (!$exitDll)
{
    Write-Error "DLL文件：$DllSourceDir 不存在"
    exit
}

#检查服务是否还在运行
if ((Get-Service|%{$_.ServiceName}) -eq $ServiceName)
{
    $NeedStartService = Get-Service $ServiceName | Where-Object {$_.Status -eq "Running"}
    if (![string]::IsNullOrEmpty($NeedStartService))
    {
        Stop-Service $NeedStartService
        #并且检查进程是否停止
        while((Get-Process|%{$_.ProcessName}) -eq $ProcessName)
        {
            [System.Threading.Thread]::Sleep(1000)
        }
    }
}
else
{
    #如果服务不存在，直接拷贝文件安装服务
    Copy-Item $DllSourceDir\*.* $ReleaseTargetDir -Recurse -Force
    cmd /c "sc create" $ServiceName "binpath="$ReleaseTargetDir"\"$ProcessName".exe"
    net start $ServiceName
    exit
}

#如果进程已经结束了，进行文件拷贝和服务安装
Copy-Item $DllSourceDir\*.* $ReleaseTargetDir -Recurse -Force
Write-Host "拷贝文件成功"
Write-Host "开始启动服务"
Start-Service $ServiceName #启动服务
$NeedStartService = Get-Service $ServiceName | Where-Object {$_.Status -eq "Running"} #获取服务是否在运行
if ([string]::IsNullOrEmpty($NeedStartService))
{
    Write-Error $ServiceName "启动失败"
    exit
}
Write-Host "启动服务成功"
while(!((Get-Process|%{$_.ProcessName}) -eq $ProcessName))
{
    [System.Threading.Thread]::Sleep(1000)
}
Write-Host "完成服务部署"